package com.rc.saas.tenant.controller.member;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.model.member.RcMemberGainSetting;
import com.rc.saas.tenant.model.member.RcMemberLevelSetting;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.member.MemeberLevelService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@Controller
@RequestMapping("/member/level")
public class MemberLevelController {
    private static Logger logger = LogManager.getLogger(MemberGainController.class);

    private String prefix = "/templates/member/level";

    @Autowired
    private MemeberLevelService memeberLevelService;

    @Autowired
    private UploadComponent uploadComponent;

    @RequestMapping("/index")
    public String index(){
        return prefix + "/level";
    }

    @RequestMapping("/addLevel")
    public String addLevel(){
        return prefix + "/addLevel";
    }

    @RequestMapping("/edit/{levelSub}")
    public String edit(Model model, @PathVariable("levelSub")String levelSub){
        RcMemberLevelSetting memberLevelSetting = memeberLevelService.selectByPrimaryKey(levelSub);
        model.addAttribute("level", memberLevelSetting);
        return prefix + "/editLevel";
    }

    @ResponseBody
    @RequestMapping("/listPageMemberLevel")
    public WebPageInfo listPageMemberLevel(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                           @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize, String levelName) {
        PageInfo<RcMemberLevelSetting> pageInfo = memeberLevelService.listPageMemberLevel(pageNo, pageSize, levelName);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出会员等级列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(String levelName,
                            @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                            @RequestParam(value = "pageSize",defaultValue = "1000") Integer pageSize, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            PageInfo<RcMemberLevelSetting> pageInfo = memeberLevelService.listPageMemberLevel(pageNo, pageSize, levelName);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("会员等级列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RcMemberLevelSetting.class).sheet("会员等级列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出会员等级列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    @ResponseBody
    @RequestMapping("/saveLevel")
    public TResponse addMemberLevel(RcMemberLevelSetting memberLevelSetting,
                                    @RequestParam(value = "file1", required = false) MultipartFile file1) {
        if ("V0".equals(memberLevelSetting.getLevelName())) {
            return TResponse.FAIL("V0为初始等级，不能添加子等级");
        }

        TenantUser user = ShiroUtils.getSessionUser();
        if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
            memberLevelSetting.setLevelLogo(imgUrl);
        }
        RcMemberLevelSetting info = memeberLevelService.selectByPrimaryKey(memberLevelSetting.getLevelSub());
        if(info!=null){
            if (StringUtil.isBlank(memberLevelSetting.getLevelLogo())){
                memberLevelSetting.setLevelLogo(info.getLevelLogo());
            }
            memberLevelSetting.setCreatedBy(info.getCreatedBy());
            memberLevelSetting.setCreatedTime(info.getCreatedTime());
            memberLevelSetting.setMemberLevel(memberLevelSetting.getLevelName());
            memeberLevelService.updateByPrimaryKey(memberLevelSetting);
        }else {
            memeberLevelService.addMemberLevel(memberLevelSetting);
        }
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/editLevel")
    public TResponse editLevel(RcMemberLevelSetting memberLevelSetting) {
        memeberLevelService.updateByPrimaryKeySelective(memberLevelSetting);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/delete")
    public TResponse delete(String levelSub) {
        memeberLevelService.deleteByPrimaryKey(levelSub);
        return TResponse.SUCCESS();
    }





}
